package com.tju.hotel.hotel.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.tju.hotel.R;
import com.tju.hotel.hotel.MyApplication;
import com.tju.hotel.hotel.util.DeviceUtils;
import com.tju.hotel.hotel.util.MD5Util;
import com.tju.hotel.hotel.util.OkHttpTool;
import com.tju.hotel.hotel.util.SPUtils;
import com.tju.hotel.hotel.util.ServiceUrls;
import com.tju.hotel.hotel.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class ForgetPasswordActivity extends AppCompatActivity {
    private Activity mActivityContext;
    private MyApplication myApplication;
    //控件
    private EditText etPhone;//文本框  手机号
    private EditText etSmsCode;//文本框  验证码
    private EditText etPassword;//文本框  密码
    private EditText etPasswordSure;//文本框 确认密码
    private TextView tvSendSms;//文本-按钮 发送验证码
    private TextView tvLogin;//文本-按钮 to登录
    private Button btnSubmit;//按钮 重置
    private TextView tvRegister;//文本-按钮 to注册

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivityContext = this;
        myApplication= (MyApplication) getApplication();
        //设置页面布局
        setContentView(R.layout.activity_forget_password);
        //获取控件
        etPhone = findViewById(R.id.et_forget_phone);
        etSmsCode = findViewById(R.id.et_forget_sms_code);
        etPassword = findViewById(R.id.et_forget_password);
        etPasswordSure = findViewById(R.id.et_forget_password_sure);
        tvSendSms = findViewById(R.id.tv_forget_send_sms);
        tvLogin = findViewById(R.id.tv_forget_login);
        btnSubmit = findViewById(R.id.btn_forget_submit);
        tvRegister = findViewById(R.id.tv_forget_register);

        //设置控件事件
        setViewListener();
    }

    //设置控件事件
    private void setViewListener() {
        //获取验证码
        tvSendSms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取手机号
                String phone = etPhone.getText() == null ? "" : etPhone.getText().toString();
                //验证数据
                if (!Tools.isMobile(phone)) {
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                //禁用发送按钮
                tvSendSms.setEnabled(false);
                //获取设备ID
                String deviceId = DeviceUtils.getDeviceUUID(mActivityContext);
                //==发送请求
                //url
                String url = ServiceUrls.getMemberMethodUrl("sendSmsValid");
                //参数
                Map<String, Object> map = new HashMap<>();
                map.put("phone", phone);
                map.put("deviceId", deviceId);
                map.put("isRegister", false);
                //发送请求
                OkHttpTool.httpPost(url, map, new OkHttpTool.ResponseCallback() {
                    @Override
                    public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                        //需要更新UI，所有要在UI线程中执行
                        mActivityContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isSuccess && responseCode == 200) {
                                    //重新发送倒计时 60s 步长1s
                                    CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
                                        //每一步的回调
                                        @Override
                                        public void onTick(long millisUntilFinished) {
                                            tvSendSms.setText(String.format(Locale.getDefault(), "重新获取(%1$d)", (millisUntilFinished / 1000)));
                                        }

                                        //定时器执行完成的回调
                                        @Override
                                        public void onFinish() {
                                            tvSendSms.setEnabled(true);//启用发送按钮
                                            tvSendSms.setText("获取验证码");
                                        }
                                    };
                                    //启动定时器
                                    timer.start();

                                    //解析服务端返回数据
                                    try {
                                        //json对象 获取code
                                        JSONObject jsonObject = new JSONObject(response);
                                        int code = jsonObject.getInt("code");
                                        if (code == 200) {
                                            //发送成功
                                            Toast.makeText(mActivityContext, "验证码发送成功，请注意查收", Toast.LENGTH_LONG).show();
                                        } else {
                                            //发送失败 json.text中存放发送失败原因
                                            String text = jsonObject.getString("text");
                                            if (code == 404) {
                                                etPhone.setError(text);
                                            }
                                            Toast.makeText(mActivityContext, text, Toast.LENGTH_LONG).show();
                                        }
                                        return;
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                Toast.makeText(mActivityContext, "验证码发送失败，请稍后再试", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });
            }
        });

        //重置按钮
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取参数
                String phone = etPhone.getText() == null ? "" : etPhone.getText().toString();
                String smsValidCode = etSmsCode.getText() == null ? "" : etSmsCode.getText().toString();
                String password = etPassword.getText() == null ? "" : etPassword.getText().toString();
                String passwordSure = etPasswordSure.getText() == null ? "" : etPasswordSure.getText().toString();
                //验证数据
                if (!Tools.isMobile(phone)) {
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                if (!Tools.isNotNull(smsValidCode)) {
                    etSmsCode.setError("请输入验证码");
                    return;
                }
                if (!Tools.isNotNull(password) || password.length() < 8) {
                    etPassword.setError("密码强度不够");
                    return;
                }
                if (!password.equals(passwordSure)) {
                    etPasswordSure.setError("两次密码不一致");
                    return;
                }
                //===发送请求
                //url
                String url = ServiceUrls.getMemberMethodUrl("resetPassword");
                //参数
                Map<String, Object> map = new HashMap<>();
                map.put("phone", phone);
                map.put("smsValidCode", smsValidCode);
                map.put("password", MD5Util.getMD5(password));
                //发送请求
                OkHttpTool.httpPost(url, map, new OkHttpTool.ResponseCallback() {
                    @Override
                    public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                        mActivityContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String strText = "无法访问服务器，请检查网络连接";
                                if (isSuccess && responseCode == 200) {
                                    //解析服务端返回的数据
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        int code = jsonObject.getInt("code");
                                        strText = jsonObject.getString("text");
                                        if (code == 200) {
                                            Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
                                            //清除内存中保存的用户信息
                                            myApplication.setLoginMember(null);
                                            //清除SharedPreferences中保存的phone和password
                                            SPUtils.remove(mActivityContext,ServiceUrls.SP_MEMBER_PHONE);
                                            SPUtils.remove(mActivityContext,ServiceUrls.SP_MEMBER_PASSWORD);
                                            //跳转都登录页面
                                            Intent intent = new Intent(mActivityContext, LoginActivity.class);
                                            startActivity(intent);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });
            }
        });
        //跳转到登录
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到登录页面
                Intent intent=new Intent(mActivityContext,LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
        //跳转到注册
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到注册页面
                Intent intent=new Intent(mActivityContext,RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
